/*
 * @Description: 接口要加上文件目录/admin/courses/xxx
 * @Author: cy
 * @Date: 2024/12/3
 */

var express = require("express");
var router = express.Router();
const { Op } = require("sequelize");

const { Course, Category, User,Chapter } = require("../../models");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");

/**
 * 公共方法：查询当前课程
 */
async function getCourse(id) {
  const course = await Course.findByPk(id);
  if (!course) {
    throw new NotFoundError(`ID: ${id}的课程未找到。`);
  }

  return course;
}


/*
 * $param
 * @return
 * @desc 课程列表，带模糊搜索
 * select * from Courses where title like '%标题 10%'`
 * 分页
 * SELECT * FROM `Courses` LIMIT offset, pageSize;
 * SELECT * FROM `Courses` LIMIT 0, 10;第一页
 * SELECT * FROM `Courses` LIMIT 10, 10;第二页
 * offset = (currentPage - 1) * pageSize
 * */
router.get("/coursesList", async function (req, res, next) {
  try {
    const query = req.query;
    // 当前是第几页，如果不传，那就是第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;

    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;

    // 计算 offset
    const offset = (currentPage - 1) * pageSize;

    // 定义查询条件
    const condition = {
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
      attributes: { exclude: ["CategoryId", "UserId"] },
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "username", "avatar"],
        },
      ],
    };
    //  where 条件中 ，通用查询条件
    if (
      Object.entries(query)?.filter(
        (e) => !["currentPage", "pageSize"]?.includes(e?.[0])
      )?.length > 0
    ) {
      let obj = {};
      Object.entries(query)
        ?.filter((e) => !["currentPage", "pageSize"]?.includes(e?.[0]))
        ?.map((item) => {
          let key = item[0];
          let value = item[1];
          obj[key] = {
            [Op.like]: `%${value}%`,
          };
        });
      condition.where = obj;
    }

    // const data = await Course.findAll(condition);
    const { count, rows } = await Course.findAndCountAll(condition);
    success(res, "查询课程列表成功", {
      courses: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }

  // res.json({
  //   status: true,
  //   message: "查询课程列表成功。",
  //   data: {
  //     courses: rows,
  //     pagination: {
  //       total: count,
  //       currentPage,
  //       pageSize,
  //     },
  //   },
  //   query,
  // });
});
/* 根据ID获取课程详情 */
router.get("/", async function (req, res, next) {
  try {
    const course = await getCourse(req.query.id);
    // 查询课程详情
    success(res, "查询课程成功。", { course });
  } catch (e) {
    // 如果没有找到，就抛出异常
    failure(res, e);
  }
});

/* 新增或者修改课程 */
router.post("/addOrUpdateCourse", async function (req, res, next) {  
  try {
    //根据ID区分创建还是更新
    if (req.body.id) {
      const course = await getCourse(req.body.id);

      // 使用 req.body 获取到用户通过 POST 提交的数据，然后创建课程
      await course.update(req.body, {
        where: { id: req.body.id },
      });
      success(res, "更新成功。", { course }, 200);
    } else {
      const course = await Course.create(req.body);
      success(res, "创建成功。", { course }, 201);
    }
  } catch (error) {
    failure(res, error);
  }
});

/* 删除课程 */
router.delete("/deleteCourseById", async function (req, res, next) {
  try {
    // 使用 req.body 获取到用户通过 POST 提交的数据，然后删除课程
    /*
     * $param
     * @return
     * @desc 或者先查询课程后，再删除，比如你想提示文字不存在，未找到，如下
     * const course = await Course.findByPk(id);
     * await course.destroy();
     * */
    //查询是否有当前课程
    const course1 = await getCourse(req.body.id);
    //查询当前课程下的章节
    const count = await Chapter.count({
      where: {
        courseId: req.body.id,
      },
    });
    if (count > 0) {
      throw new Error(`ID: ${req.body.id}的课程下有章节，不能删除。`);
    }
    const course = await Course.destroy({ where: { id: req.body.id } });
    //
    // res.status(200).json({
    //   status: true,
    //   message: "操作成功。",
    //   data: course,
    // });
    success(res, "删除课程成功。");
  } catch (error) {
    // res.status(500).json({
    //   status: false,
    //   message: "操作失败。",
    //   errors: [error.message],
    // });
    failure(res, error);
  }
});

module.exports = router;
